package com.dhc.shiro.realm;

import com.dhc.shiro.pojo.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * 自定义Realm(加密)
 */
public class PasswordRealm extends AuthorizingRealm {

    @Override
    public String getName() {
        return "passwordRealm";
    }

    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        User user = new User();
        user.setUsername("zhangsan");
        //加密方式:md5+盐(账号)+散列次数(3次)
        user.setPassword("b51ae3e5279bc66eae7a4fe2600ab0b1");
        //用户名不同,即未查询到此用户名的用户信息,返回null,则报错未找到此用户
        if (!user.getUsername().equals(username)) {
            return null;
        }
        //封装信息到info 参数:1用户对象(数据库查询)2用户密码(数据库查询)3盐(加密添加的盐即账号)4Realm方法名
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(),ByteSource.Util.bytes("zhangsan"),getName());
        return info;
    }
}
